/**
 * @FileName: CmccRewardService.java
 * @Author
 * @Description:
 * @Date 2016年3月28日 下午3:01:48
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.service.ds;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.hpclub.server.ext.fastexcel.FastExcelRender;
import cn.hpclub.server.model.SalesPromotion;
import cn.hpclub.server.service.ds.DateUtils.SyncParams;

public class CmccRewardService{
    private static final int                  PAGE_SIZE         = 5000;
    private static final String               FILE_EXTENSION    = ".xlsx";
    private static final String               OUT_PUT_FILE_NAME = "大掌柜酬金数据";
    private static final String               REWARD_DIR        = "reward/";
    private static Logger                     logger            = LoggerFactory.getLogger(CmccRewardService.class);

    private volatile static boolean           isExporting       = false;
    private volatile static CmccRewardService instance;

    private CmccRewardService(){}

    public static CmccRewardService getInstance(){
        if(instance == null){
            synchronized(CmccRewardService.class){
                if(instance == null){
                    instance = new CmccRewardService();
                }
            }
        }
        return instance;
    }

    public boolean isExporting(){
        return isExporting;
    }

    public void exportLastestMonthData(final int month){
        synchronized(this){
            if(isExporting){
                logger.debug("Exporting..., please waiting...");
                return;
            }
            new Thread(){
                public void run(){
                    isExporting = true;
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(new Date());
                    for(int i = 0; i < month; i++){
                        logger.debug("date:" + calendar.getTime());
                        exportData(calendar.getTime());
                        calendar.add(Calendar.MONTH, -1);
                    }
                    isExporting = false;
                }
            }.start();
        }
    }

    private void exportData(Date date){
        ConcurrentHashMap<String, String> searchMap = new ConcurrentHashMap<String, String>();
        searchMap.put("businessCodeNotEqual-1362", "1362");
        searchMap.put("businessCodeNotEqual-4001", "4001");
        SyncParams params = DateUtils.getLastMonthParams(date);
        searchMap.put("startTime", params.start);
        searchMap.put("endTime", params.end);

        DsLog.log("酬金数据导出：" + params.toString());
        SalesPromotion salesPromotion = new SalesPromotion();
        String select = salesPromotion.getSelectStatementForCMCCReward();
        String sqlExceptSelect = salesPromotion.getExceptSelectStatementForCMCCBussiness(searchMap);
        logger.debug("sqlExceptSelect=" + sqlExceptSelect);
        String filename = OUT_PUT_FILE_NAME + params.tag + FILE_EXTENSION;
        export(select, sqlExceptSelect, filename);
    }

    public List<File> getRewardFiles(){
        File dir = new File(getDirPath());
        File[] files = dir.listFiles();
        List<File> list = new ArrayList<File>();
        for(File file : files){
            if(file.isFile()){
                list.add(file);
            }
        }
        Collections.sort(list, new Comparator<File>(){

            @Override
            public int compare(File file1, File file2){
                return file2.getName().compareTo(file1.getName());
            }

        });
        return list;
    }

    private void export(String select, String sqlExceptSelect, String fileName){
        String[] headers = { "业务类型", "业务编码", "业务名称", "号码", "金额", "办理时间 ", "办理结果", "网厅流水", "酬金编码", "BOSS模块代码", "参数",
                "结酬分类编码", "渠道标识", "渠道名称" };
        String[] columns = { "businessType", "business_code", "tariff", "phone_no", "amount", "cmcc_time", "resultCode",
                "order_id", "NumCode", "moudlecode", "paramter", "rewardTypeCode", "qudaoFlag", "qudaoName" };

        File file = getFile(fileName);
        FileOutputStream fos = null;
        try{
            fos = new FileOutputStream(file);
            long exportExcelStart = System.currentTimeMillis();
            FastExcelRender excel = getExcelRender(select, sqlExceptSelect);
            excel.sheetName("酬金报表").version("1.0").headers(headers).columns(columns).fileName(file.getName()).os(fos);
            excel.render();
            DsLog.log("酬金数据导出:导出成功,导出文件:" + file.getName());
            logger.debug("exportExcel use time:" + (System.currentTimeMillis() - exportExcelStart));
        }
        catch(Exception e){
            logger.debug(e.getMessage());
            file.delete();
        }
        finally{
            closeOutputStream(fos);
        }
    }

    private void closeOutputStream(OutputStream os){
        if(os != null){
            try{
                os.close();
            }
            catch(IOException e){
                e.printStackTrace();
            }
        }
    }

    private File getFile(String fileName){
        String filePath = getDirPath() + "/" + fileName;
        logger.debug("file url=" + filePath);
        File file = new File(filePath);
        return file;
    }

    private FastExcelRender getExcelRender(String select, String sqlExceptSelect){
        FastExcelRender excel = new FastExcelRender(new FastExcelRender.AppendMoreData(){
            private int num = 0;

            @Override
            public List<?> append(){
                long start = System.currentTimeMillis();
                List<?> list = SalesPromotion.dao
                        .find(String.format("%s %s LIMIT %d, %d", select, sqlExceptSelect, num * PAGE_SIZE, PAGE_SIZE));
                logger.debug("num=" + num + ",size=" + list.size() + ",query use time:"
                        + (System.currentTimeMillis() - start));
                if(num > 1 && list.isEmpty()){
                    return null;
                }
                num++;
                return list;
            }
        });
        return excel;
    }

    /**
     * @Title: getDirPath
     * @Description:获取文件存储目录
     * @return String
     */
    public String getDirPath(){
        String dirPath = Common.getRootDir() + REWARD_DIR;
        Common.checkDir(dirPath);
        return dirPath;
    }
}
